<template>
  <!-- 设计师订单首页 -->
  <div class="t_1558420973068 box">
    <titleBar title="我的订单"
              :noBack="true"  :noFixed="true" />
    <van-tabs background="#5E8EFE"
              color="#FFFFFF"
              sticky
              :offset-top="0"
              v-model="tabindex"
              @change="checktab"
              swipeable
              title-active-color="#FFFFFF"
              title-inactive-color="#FFFFFF"
              style="z-index: 20">
      <van-tab v-for="(item,index) in tabsList"
               :key="index"
               :title="item.name">

        <!-- v-if="orderList.length !== 0" -->
        <van-list  :loading="loading"
                  class="list"
                  :finished="finished"
                  finished-text="没有更多了"
                  @load="onLoad">
          <van-pull-refresh v-model="isLoading"
                            @refresh="onRefresh" :style="orderList.length === 0 ? {} : {
                                paddingTop: '.24rem',
                                minHeight: 'calc(100vh - .9rem - 44px - 50px)'
                            }">
            <order-card :form="orderItem"
                        :groupUids="groupUids"
                        @open_popup="open_popup(orderItem.uid)"
                        @updateOrder="updateOrder"
                        @successPay="successPay"
                        @changePay="changePay"
                        type="1"
                        v-for="(orderItem, index) in orderList"
                        :key="index" />
          </van-pull-refresh>
        </van-list>
        <!-- <div v-if="orderList.length === 0" class="data-nil">
          暂无数据
        </div> -->
        <!-- <div class="noOrder"
                v-show="order=='0'">
                <div class="orderimg">
                    <img src="@/assets/img/performance/homePage/noorder.png" width="100%" alt="">
                </div>
                <div class="fz4 wordsGray notitle">暂无订单</div>
            </div> -->
      </van-tab>
    </van-tabs>
    <reselect-popup :showPopup="showPopup"
                    :orderUid="orderUid"
                    @close_popup="close_popup"></reselect-popup>
    <main-nav />

    <div v-if="isPayWay"
         class="upDoor-popup pay-way-box">
      <div class="mask"></div>
      <div class="inner">
        <div class="flex flex-space-x handle-head">
          <div></div>
          <div class="title-name">请选择支付方式</div>
          <div class="close-block"
               v-on:click="isPayWay = false, payRun = false">
            <i class="iconfont icon-guanbi1"></i>
          </div>
        </div>
        <div class="pay-list">
          <div class="pay-item flex flex-center-y flex-space-x"
               v-for="(item, index) in payWayList"
               :key="index"
               v-on:click="switchPayWay(index)">
            <div class="flex flex-center-y">
              <i v-if="item.icon"
                 class="pay-way-wconfont iconfont"
                 :class="[item.icon]"
                 :style="item.styles"></i>
              <img class="pay-way-wconfont"
                   v-if="item.img"
                   :src="item.img" />
              <span>{{item.name}}</span>
            </div>
            <i v-if="payOrderPayWayActiveIndex === index"
               class="select-block iconfont icon-dui"></i>
            <i v-else></i>
          </div>
          <div class="pay-item flex flex-center-y flex-space-x"
               v-on:click="addBank">
            <div class="flex flex-center-y">
              <img class="pay-way-wconfont"
                   src="@/assets/img/performance/homePage/bank.png" />
              <span>银行卡账号</span>
            </div>
            <div class="add"
                 v-on:click="addBank">
              <span>添加</span>
              <i class="iconfont icon-iconfonticonfonti2copycopy"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>
<script>
import titleBar from "@/components/title_bar/index.vue";
import orderCard from "@/components/designer/orderCenter/orderCard.vue";
import reselectPopup from "@/components/designer/orderCenter/reselectPopup";
import { getToken, getuserUid, getRole } from "@/utils/auth";
import { defaultPayWayList } from "@/pages/performance/homePage/children_page/pay_order/constant.js";
import mainNav from "@/components/designer/mainNav";
import { Copy } from "@/utils/object";
import { mapState, mapMutations } from "vuex";
import { paying } from "@/utils/pay.js";
import { getRemind } from "@/utils/chat.js";
export default {
  data() {
    return {
      groupUids: getRemind(),
      isLoading: false,
      showPopup: false,
      tabsList: [
        {
          name: "全部",
          status: ""
        },
        {
          name: "待服务",
          status: "1"
        },
        {
          name: "进行中",
          status: "2"
        },
        {
          name: "结算/收图",
          status: "4"
        },
        {
          name: "待评价",
          status: "8"
        },
        {
          name: "退款/关闭",
          status: "6"
        },
        {
          name: "已完成",
          status: "5"
        }
      ],
      orderList: [],
      loading: false,
      finished: false,
      tabindex: 0,
      order: "0",
      oldParams: null,
      // fixedHeight: "43"
      status: "",
      pageNum: 0,
      pageSize: 3,
      payWayList: defaultPayWayList,
      isPayWay: false,
      // payOrderPayWayActiveIndex: 0,
      orderItem: "",
      orderUid: "",
      // 在支付中
      payRun: false,
      currentPayType: "",
      // 数据是否在加载中
      loadingList: false,
      // 循环监听订单
      isLoopOrder: false,
    };
  },
  created() {
    // TODO 模拟支付
    // this.bankList('834532c343a911e9855d6045cb8a6182')
    this.setTabIndex(1);
    let loop = () => {
      if(this.isLoopOrder){
        this.waitchOrder()
        setTimeout(loop, 5e3)
      }
    }
    this.isLoopOrder = true
    loop()
  },
  components: {
    mainNav,
    orderCard,
    reselectPopup,
    titleBar
  },
  computed: {
    ...mapState(["payOrderPayWayActiveIndex"])
  },
  methods: {
    async waitchOrder(){
      let params = {
        userUid: getuserUid(),
        role: getRole()
      }
      let response
      try {      
        response = await HTTP('app/buser/getorderChangeMsg', params)
      } catch (error) {
        console.log(error)
        this.$toast('服务器开小差了')
        return
      }
      // console.log('---监听结果response----')
      // console.log(response)
      if(response.code !== 200){
        // this.$toast(response.msg || '异常')
        console.log('%c监听失败：' + (response.msg || '异常'), 'color: red')
        return
      }
      // console.log('操作成功')
      response.data.forEach((newRow) => {
        this.orderList = this.orderList.map((oldRow) => {
          return oldRow.uid === newRow.uid ? newRow : oldRow
        })
      })
    },
    ...mapMutations(["UPDATE", "setTabIndex"]),
    successPay(item, type) {
      this.currentPayType = type;
      // loading
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        mask: true,
        loadingType: "spinner",
        message: "加载中"
      });
      this.orderItem = item;
      // 加载银行卡列表
      this.bankList(item.userUid);
    },
    changePay(item, type) {
      this.currentPayType = type;
      this.orderItem = item;
      // 加载银行卡列表
      this.bankList(item.userUid);
    },
    addBank() {
      // if (!this.businessUserUid) {
      //   this.$toast("加载中");
      //   return;
      // }
      this.$router.push("/performance/bindbank?type=3&userUid=" + getuserUid());
    },
    switchPayWay(index) {
      if (this.payRun) {
        this.$toast("支付中");
        console.log("锁");
        return;
      }
      // this.UPDATE(['payOrderPayWayActiveIndex', index])
      // this.payOrderPayWayActiveIndex = index;
      // this.isPayWay = false
      // 处理支付
      let payType = index === 0 ? 2 : index === 1 ? 1 : 3;
      switch (this.currentPayType) {
        case "changeImagePay": {
          this.updateImagePay(payType, index);
          break;
        }
        case "getImage": {
          this.getImages(payType, index);
          break;
        }
        default: {
          console.log("匹配异常");
        }
      }
    },
    // 改图支付
    async updateImagePay(payType, index) {
      let params = {
        orderUid: this.orderItem.uid,
        userUid: getuserUid(),
        payType
      };
      this.payRun = true;
      if (payType === 3) {
        params.bankCardUid = this.payWayList[index].uid;
      }
      let payResponse;
      try {
        payResponse = await HTTP("app/buser/payGOrder", params);
      } catch (error) {
        console.log(error);
        this.$toast("服务器开小差了");
        return;
      }
      if(payResponse.code !== 200){
        this.$toast(payResponse.msg || '异常')
        this.payRun = false;
        return
      }
      // 处理请求
      let outTradeNo = payResponse.msg;
      this.payRun = false;
      paying(
        {
          url: "app/buser/payGOrder",
          params
        },
        payType,
        payResponse.data,
        outTradeNo
      );
    },
    // 收图
    async getImages(payType, index) {
      console.log("-------确认收图----------");
      console.log(this.orderItem);
      console.log(this.order);
      let params = {
        userUid: getuserUid(),
        orderUid: this.orderItem.uid,
        payType: this.orderItem.subsequentAmount > 0 ? payType : ""
      };
      if (payType === 3) {
        params.bankCardUid = this.payWayList[index].uid;
      }

      this.payRun = true;
      // 请求支付信息
      let payResponse = await HTTP("order/updateOrdersStatus", params);
      console.log(this.orderItem.subsequentAmount);
      console.log(params);
      console.log(payResponse);
      if(payResponse.code !== 200){
        this.$toast(payResponse.msg || '异常')
        this.payRun = false;
        return
      }
      // 处理请求
      let outTradeNo = payResponse.msg;
      this.payRun = false;
      paying(
        {
          url: "order/updateOrdersStatus",
          params
        },
        payType,
        payResponse.data,
        outTradeNo
      );
    },
    async bankList(userUid) {
      let params = {
        userUid
      };
      let bankResponse;
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        mask: true,
        loadingType: "spinner",
        message: "加载中"
      })
      try {
        // TEST toast
        // await new Promise(e => {
        //   window.setTimeout(e, 1e3);
        // });
        bankResponse = await HTTP("app/user/getUserBankCards", params);
        if (bankResponse.code !== 200) {
          this.$toast(bankResponse.msg);
          return;
        }
        console.log("银行卡列表");
        console.log(bankResponse.data);
        this.payWayList = [
          ...defaultPayWayList,
          ...bankResponse.data.map(e => {
            return {
              ...e,
              name: `${
                e.bankName ? e.bankName : "银行卡"
              }(${e.bankCardNumber.substr(e.bankCardNumber.length - 4)})`,
              img: require("@/assets/img/performance/homePage/bank.png")
            };
          })
        ];
        // this.orightBankList = bankResponse.data
        this.isPayWay = true;
        toast.clear()
      } catch (error) {
        toast.clear()
        this.$toast("数据开小差了");
        console.log(error);
      }
    },
    //下拉刷新
    onRefresh() {
      let params = {
        ...this.oldParams,
        status: this.status,
        pageNum: 1
      };
      // this.$toast.loading({ mask: true, message: "加载中..." });
      setTimeout(() => {
        this.isLoading = false;
        this.pageNum = 1;
        this.finished = false;
        this.requestList(params, this.handleList.bind(this, params));
      }, 500);
    },
    checktab(index) {
      // this.orderList = [];
      this.pageNum = 0;
      this.finished = false;
      if (index == 0) {
        this.status = "";
      } else if (index == 3) {
        this.status = "4";
      } else if (index == 4) {
        this.status = "8";
      } else if (index == 5) {
        this.status = "6";
      } else if (index == 6) {
        this.status = "5";
      } else {
        this.status = index ? index : index;
      }      
      // TODO 正确应该这样写    this.status = this.tabsList[index] 
      this.onLoad();
      return;

      this.tabindex = index;
      this.pageNum = 1;
      this.finished = false;

      let params = {
        ...this.oldParams,
        status: this.status,
        pageNum: 1
      };
      this.requestList(params, this.handleList.bind(this, params));
    },
    onLoad() {
      this.loading = true;
      this.pageNum += 1;
      let params = {
        status: this.status,
        userUid: getuserUid(),
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      console.log(params);
      setTimeout(() => {
        this.requestList(params, this.handleList.bind(this, params));
      }, 1e2);
    },
    updateOrder() {
      this.pageNum = 1;
      this.finished = false;
      let params = {
        ...this.oldParams,
        status: this.status,
        pageNum: 1
      };
      setTimeout(() => {
        this.requestList(params, this.handleList.bind(this, params));
      }, 5e2);
    },
    handleList(params, data) {
      this.loading = false;
      this.$toast.clear()
      if (params.pageNum === 1) {
        this.orderList = [];

        if (data && data.length === 0) {
          this.finished = true;
        } else {
          setTimeout(() => {
            this.orderList = data;
          }, 100);
        }
      } else {
        this.orderList.push(...data);
        if (data && data.length === 0) {
          this.finished = true;
        }
      }
    },
    async requestList(params, cb) {
      this.oldParams = Copy(params);
      try {
        let responseList = await HTTP("selectOrderListByStatus", params);
        if (responseList.code !== 200) {
          this.$toast(responseList.msg || "服务器异常");
          return;
        }
        // console.log('---params.status---')
        // console.log(params.status)
        // console.log('----当前位置 status----')
        // console.log(this.tabsList[this.tabindex].status)
        // 只有位置相同才渲染
        if(params.status == this.tabsList[this.tabindex].status){
          cb && cb(Copy(responseList.data.list));
        }
        this.loadingList = true
      } catch (error) {
        this.$toast("数据开小差了");
        console.log(error);
        cb && cb();
      }
    },
    //打开弹框
    open_popup(uid) {
      this.orderUid = uid;
      this.showPopup = true;
    },
    //关闭弹框
    close_popup() {
      this.showPopup = false;
    }
  },
  beforeMount() {
    // var h = document.documentElement.clientHeight || document.body.clientHeight;
    // this.curHeight = h - this.fixedHeight + "px"; //减去页面上固定高度height
  },
  destroyed(){
    this.isLoopOrder = false
  }
};
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>